import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Avatar,
  Upload,
  message,
  Row,
  Col,
  Divider,
  Typography,
  Space,
  Tag,
  Spin,
  Alert,
  Tabs
} from 'antd';
import {
  UserOutlined,
  EditOutlined,
  SaveOutlined,
  CameraOutlined,
  MailOutlined,
  BookOutlined,
  TrophyOutlined,
  HeartOutlined,
  CalendarOutlined,
  PlusOutlined
} from '@ant-design/icons';
import { userService } from '../services/api';
import { useAuth } from '../store/AuthContext';
import { INTEREST_OPTIONS } from '../constants/interests';
import type { UploadProps } from 'antd';

// 课表相关组件
import ScheduleUpload from '../components/ScheduleUpload';
import ScheduleTable from '../components/ScheduleTable';
import ScheduleVisualization from '../components/ScheduleVisualization';
import CourseEditModal from '../components/CourseEditModal';
import { scheduleService } from '../services/scheduleService';
import { Course, ScheduleData, AIAnalysisResult } from '../types/schedule';

const { Title, Text } = Typography;
const { Option } = Select;

interface UserProfile {
  id: number;
  username: string;
  email: string;
  gender?: string;
  grade?: string;
  major?: string;
  dream_career?: string;
  interests?: string[];
  avatar?: string;
  created_at?: string;
}

const Profile: React.FC = () => {
  const { updateUser } = useAuth();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [editing, setEditing] = useState(false);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  
  // 课表相关状态
  const [scheduleData, setScheduleData] = useState<ScheduleData[] | null>(null);
  const [currentSchedule, setCurrentSchedule] = useState<ScheduleData | null>(null);
  const [scheduleLoading, setScheduleLoading] = useState(false);
  const [courseEditModalVisible, setCourseEditModalVisible] = useState(false);
  const [editingCourse, setEditingCourse] = useState<Course | null>(null);
  const [activeTab, setActiveTab] = useState('profile');

  // 获取用户信息
  const loadProfile = useCallback(async () => {
    try {
      setLoading(true);
      const response = await userService.getProfile() as any;
      console.log('Profile API响应:', response);
      
      // 由于响应拦截器已经返回了response.data，所以直接使用response
      if (response && response.message && response.user) {
        const userData = response.user;
        setProfile(userData);
        form.setFieldsValue({
          username: userData.username,
          email: userData.email,
          gender: userData.gender,
          grade: userData.grade,
          major: userData.major,
          dream_career: userData.dream_career,
          interests: userData.interests || []
        });
      } else {
        console.error('API响应格式不正确:', response);
        message.error('用户信息格式错误');
      }
    } catch (error: any) {
      console.error('加载用户信息失败:', error);
      message.error('加载用户信息失败');
    } finally {
      setLoading(false);
    }
  }, [form]);

  // 更新用户信息
  const handleSave = async (values: any) => {
    try {
      setSaving(true);
      const response = await userService.updateProfile(values) as any;
      if (response && response.message) {
        message.success('个人信息更新成功');
        setEditing(false);
        await loadProfile(); // 重新加载用户信息
        // 更新AuthContext中的用户信息
        if (profile) {
          updateUser({
            ...profile,
            ...values
          });
        }
      }
    } catch (error: any) {
      console.error('更新用户信息失败:', error);
      message.error('更新用户信息失败');
    } finally {
      setSaving(false);
    }
  };

  // 头像上传处理
  const handleAvatarUpload = async (file: File) => {
    try {
      const response = await userService.uploadAvatar(file) as any;
      if (response && response.message) {
        message.success('头像上传成功');
        // 重新加载用户信息
        await loadProfile();
        return false; // 阻止默认上传行为
      }
    } catch (error: any) {
      console.error('头像上传失败:', error);
      message.error('头像上传失败');
      return false;
    }
  };

  // 头像上传配置
  const uploadProps: UploadProps = {
    name: 'avatar',
    listType: 'picture-circle',
    showUploadList: false,
    beforeUpload: (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/webp';
      if (!isJpgOrPng) {
        message.error('只能上传 JPG/PNG/WebP 格式的图片!');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过 2MB!');
        return false;
      }
      return handleAvatarUpload(file);
    },
  };

  // 课表相关函数
  const loadSchedule = useCallback(async () => {
    try {
      setScheduleLoading(true);
      const schedules = await scheduleService.getUserSchedule();
      setScheduleData(schedules);
      // 如果有课表，默认选择第一个
      if (schedules && schedules.length > 0) {
        setCurrentSchedule(schedules[0]);
      }
    } catch (error) {
      console.error('加载课表失败:', error);
    } finally {
      setScheduleLoading(false);
    }
  }, []);

  const handleAnalysisComplete = async (result: AIAnalysisResult): Promise<void> => {
    const hideLoading = message.loading('正在保存课表到数据库...', 0);
    
    try {
      const newScheduleData: ScheduleData = {
        id: `schedule_${Date.now()}`,
        userId: profile?.id || 0,
        title: result.semesterInfo?.semester || '2024春季课表',
        semester: result.semesterInfo?.semester || '2024春季',
        startWeek: result.semesterInfo?.totalWeeks ? 1 : 1,
        totalWeeks: result.semesterInfo?.totalWeeks || 20,
        startDate: result.semesterInfo?.startDate || undefined,
        endDate: result.semesterInfo?.endDate || undefined,
        classTimes: result.semesterInfo?.classTimes || {},
        duration: result.semesterInfo?.duration || 45,
        courses: result.courses,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      // 显示保存进度
      message.info('正在保存课表主信息...');
      await scheduleService.saveSchedule(newScheduleData);
      
      // 显示重新加载进度
      message.info('正在重新加载课表列表...');
      await loadSchedule();
      
      setCurrentSchedule(newScheduleData);
      setActiveTab('schedule');
      
      hideLoading();
      message.success(`课表保存成功！共保存了 ${result.courses.length} 门课程`);
    } catch (error) {
      hideLoading();
      console.error('保存课表失败:', error);
      message.error('保存课表失败: ' + (error as any)?.message || '未知错误');
      throw error; // 重新抛出错误，让调用方知道保存失败
    }
  };

  const handleAnalysisError = (error: string) => {
    message.error(error);
  };

  const handleEditCourse = (course: Course) => {
    setEditingCourse(course);
    setCourseEditModalVisible(true);
  };

  const handleSaveCourse = async (course: Course) => {
    try {
      if (currentSchedule) {
        await scheduleService.updateCourse(course.id, course);
        
        // 重新加载课表列表
        await loadSchedule();
        setCourseEditModalVisible(false);
        setEditingCourse(null);
        message.success('课程信息更新成功');
      }
    } catch (error) {
      console.error('更新课程失败:', error);
      message.error('更新课程失败');
    }
  };

  const handleAddCourse = () => {
    setEditingCourse(null);
    setCourseEditModalVisible(true);
  };

  // 使用统一的兴趣爱好选项
  const interestOptions = INTEREST_OPTIONS;

  // 年级选项
  const gradeOptions = [
    '大一', '大二', '大三', '大四', '研一', '研二', '研三', '博士', '已毕业'
  ];

  useEffect(() => {
    loadProfile();
    loadSchedule();
  }, [loadProfile, loadSchedule]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>加载用户信息中...</div>
      </div>
    );
  }

  if (!profile) {
    return (
      <Alert
        message="加载失败"
        description="无法加载用户信息，请刷新页面重试"
        type="error"
        showIcon
      />
    );
  }

  const tabItems = [
    {
      key: 'profile',
      label: (
        <span>
          <UserOutlined />
          个人信息
        </span>
      ),
      children: (
        <Row gutter={[24, 24]}>
        {/* 左侧：头像和基本信息 */}
        <Col xs={24} lg={8}>
          <Card>
            <div style={{ textAlign: 'center' }}>
              <Upload {...uploadProps}>
                <div style={{ position: 'relative', display: 'inline-block' }}>
                  <Avatar
                    size={120}
                    src={profile.avatar ? `http://localhost:3002${profile.avatar}` : undefined}
                    icon={<UserOutlined />}
                    style={{ fontSize: '48px' }}
                    crossOrigin="anonymous"
                  />
                  <div
                    style={{
                      position: 'absolute',
                      bottom: 0,
                      right: 0,
                      background: '#1890ff',
                      borderRadius: '50%',
                      width: '32px',
                      height: '32px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      cursor: 'pointer',
                      border: '2px solid #fff'
                    }}
                  >
                    <CameraOutlined style={{ color: '#fff', fontSize: '14px' }} />
                  </div>
                </div>
              </Upload>
              
              <Title level={4} style={{ marginTop: '16px', marginBottom: '8px' }}>
                {profile.username}
              </Title>
              
              <Text type="secondary">
                <MailOutlined style={{ marginRight: '4px' }} />
                {profile.email}
              </Text>

              <Divider />

              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <div>
                  <Text strong>注册时间：</Text>
                  <Text type="secondary">
                    {profile.created_at ? new Date(profile.created_at).toLocaleDateString() : '未知'}
                  </Text>
                </div>
                
                {profile.gender && (
                  <div>
                    <Text strong>性别：</Text>
                    <Text type="secondary">
                      {profile.gender === 'male' ? '男' : profile.gender === 'female' ? '女' : '其他'}
                    </Text>
                  </div>
                )}

                {profile.grade && (
                  <div>
                    <Text strong>年级：</Text>
                    <Text type="secondary">{profile.grade}</Text>
                  </div>
                )}

                {profile.major && (
                  <div>
                    <Text strong>专业：</Text>
                    <Text type="secondary">{profile.major}</Text>
                  </div>
                )}

                {profile.dream_career && (
                  <div>
                    <Text strong>理想职业：</Text>
                    <Text type="secondary">{profile.dream_career}</Text>
                  </div>
                )}
              </Space>

              {profile.interests && profile.interests.length > 0 && (
                <>
                  <Divider />
                  <div>
                    <Text strong style={{ display: 'block', marginBottom: '8px' }}>
                      <HeartOutlined style={{ marginRight: '4px' }} />
                      兴趣爱好：
                    </Text>
                    <div>
                      {profile.interests.map((interest, index) => (
                        <Tag key={index} color="blue" style={{ marginBottom: '4px' }}>
                          {interest}
                        </Tag>
                      ))}
                    </div>
                  </div>
                </>
              )}
            </div>
          </Card>
        </Col>

        {/* 右侧：编辑表单 */}
        <Col xs={24} lg={16}>
          <Card
            title={
              <Space>
                <EditOutlined />
                编辑个人信息
                {!editing && (
                  <Button
                    type="primary"
                    icon={<EditOutlined />}
                    onClick={() => setEditing(true)}
                    size="small"
                  >
                    编辑
                  </Button>
                )}
              </Space>
            }
            extra={
              editing && (
                <Space>
                  <Button onClick={() => setEditing(false)}>
                    取消
                  </Button>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    loading={saving}
                    onClick={() => form.submit()}
                  >
                    保存
                  </Button>
                </Space>
              )
            }
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSave}
              disabled={!editing}
            >
              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="用户名"
                    name="username"
                    rules={[
                      { required: true, message: '请输入用户名' },
                      { min: 3, max: 20, message: '用户名长度为3-20个字符' }
                    ]}
                  >
                    <Input prefix={<UserOutlined />} />
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="邮箱"
                    name="email"
                    rules={[
                      { required: true, message: '请输入邮箱' },
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input prefix={<MailOutlined />} disabled />
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="性别"
                    name="gender"
                  >
                    <Select placeholder="请选择性别" allowClear>
                      <Option value="male">男</Option>
                      <Option value="female">女</Option>
                      <Option value="other">其他</Option>
                    </Select>
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="年级"
                    name="grade"
                  >
                    <Select placeholder="请选择年级" allowClear>
                      {gradeOptions.map(grade => (
                        <Option key={grade} value={grade}>{grade}</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Row gutter={16}>
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="专业"
                    name="major"
                    rules={[
                      { max: 50, message: '专业名称不能超过50个字符' }
                    ]}
                  >
                    <Input prefix={<BookOutlined />} placeholder="请输入专业" />
                  </Form.Item>
                </Col>
                
                <Col xs={24} sm={12}>
                  <Form.Item
                    label="理想职业"
                    name="dream_career"
                    rules={[
                      { max: 50, message: '理想职业不能超过50个字符' }
                    ]}
                  >
                    <Input prefix={<TrophyOutlined />} placeholder="请输入理想职业" />
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                label="兴趣爱好"
                name="interests"
              >
                <Select
                  mode="multiple"
                  placeholder="请选择兴趣爱好"
                  style={{ width: '100%' }}
                  allowClear
                >
                  {interestOptions.map(interest => (
                    <Option key={interest} value={interest}>{interest}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Form>
          </Card>
        </Col>
      </Row>
      ),
    },
    {
      key: 'schedule',
      label: (
        <span>
          <CalendarOutlined />
          课表管理
        </span>
      ),
      children: (
        <div>
          {!scheduleData || scheduleData.length === 0 ? (
            <ScheduleUpload
              onAnalysisComplete={handleAnalysisComplete}
              onError={handleAnalysisError}
            />
          ) : (
            <div>
              {/* 课表选择器 */}
              <div style={{ marginBottom: '16px' }}>
                <Space wrap>
                  <span>选择课表：</span>
                  <Select
                    value={currentSchedule?.id}
                    onChange={(value) => {
                      const selected = scheduleData.find(s => s.id === value);
                      setCurrentSchedule(selected || null);
                    }}
                    style={{ minWidth: '200px' }}
                  >
                    {scheduleData.map(schedule => (
                      <Option key={schedule.id} value={schedule.id}>
                        {schedule.title} ({schedule.semester})
                      </Option>
                    ))}
                  </Select>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    onClick={() => setScheduleData(null)}
                  >
                    上传新课表
                  </Button>
                </Space>
              </div>

              {currentSchedule && (
                <div>
                  <div style={{ marginBottom: '16px' }}>
                    <Space>
                      <Button 
                        type="primary" 
                        icon={<PlusOutlined />}
                        onClick={handleAddCourse}
                      >
                        添加课程
                      </Button>
                      <Button 
                        danger
                        onClick={async () => {
                          try {
                            await scheduleService.deleteSchedule(currentSchedule.id);
                            await loadSchedule();
                            setCurrentSchedule(null);
                            message.success('课表删除成功');
                          } catch (error) {
                            message.error('删除课表失败');
                          }
                        }}
                      >
                        删除课表
                      </Button>
                    </Space>
                  </div>
                  
                  <ScheduleVisualization
                    courses={currentSchedule.courses}
                    startWeek={currentSchedule.startWeek}
                    totalWeeks={currentSchedule.totalWeeks}
                  />
                  
                  <div style={{ marginTop: '24px' }}>
                    <ScheduleTable
                      courses={currentSchedule.courses}
                      loading={scheduleLoading}
                      onEdit={handleEditCourse}
                    />
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      ),
    }
  ];

  return (
    <div style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <Title level={2} style={{ marginBottom: '24px' }}>
        <UserOutlined style={{ marginRight: '8px' }} />
        个人信息
      </Title>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={tabItems}
        size="large"
      />

      <CourseEditModal
        visible={courseEditModalVisible}
        course={editingCourse}
        onCancel={() => {
          setCourseEditModalVisible(false);
          setEditingCourse(null);
        }}
        onSave={handleSaveCourse}
      />
    </div>
  );
};

export default Profile;